package com.cgw.room;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.cgw.room.util.FileOperator;
import com.cgw.room.widget.BaseFragment;

public class NetFragment extends BaseFragment {

    private TextView firstIP;
    private TextView secondIP;
    private TextView thirdIP;
    private TextView fourthIP;
    private TextView mTextPort;
    private TextView mTextPortRecv;

    private String sFirstIP = "";
    private String sSecondIP = "";
    private String sThirdIP = "";
    private String sFourthIP = "";

    private Button mBtnBack = null;
    private Button mBtnOK = null;
    private Button mBtnCancel = null;
    private Button mBtnNum0 = null;
    private Button mBtnNum1 = null;
    private Button mBtnNum2 = null;
    private Button mBtnNum3 = null;
    private Button mBtnNum4 = null;
    private Button mBtnNum5 = null;
    private Button mBtnNum6 = null;
    private Button mBtnNum7 = null;
    private Button mBtnNum8 = null;
    private Button mBtnNum9 = null;
    private Button mBtnNumBack = null;
    private Button mBtnNumOK = null;


    @SuppressLint("WrongViewCast")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_net, null);
        fragmentActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        Log.i("[Route]", "NetCreate");

        firstIP = view.findViewById(R.id.firstIPfield);
        secondIP = view.findViewById(R.id.secondIPfield);
        thirdIP = view.findViewById(R.id.thirdIPfield);
        fourthIP = view.findViewById(R.id.fourthIPfield);
        mTextPort = view.findViewById(R.id.net_port);
        mTextPortRecv = view.findViewById(R.id.net_port_recv);

        Log.i("[Route]", MainApp.getIP() + " : " + MainApp.PORT);

        setIPEditTextListener();

        firstIP.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()){secondIP.setSelected(false);thirdIP.setSelected(false);fourthIP.setSelected(false);
                mTextPort.setSelected(false);mTextPortRecv.setSelected(false);}
        });
        secondIP.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()){firstIP.setSelected(false);thirdIP.setSelected(false);fourthIP.setSelected(false);
                mTextPort.setSelected(false);mTextPortRecv.setSelected(false);}
        });
        thirdIP.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()){firstIP.setSelected(false);secondIP.setSelected(false);fourthIP.setSelected(false);
                mTextPort.setSelected(false);mTextPortRecv.setSelected(false);}
        });
        fourthIP.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()){firstIP.setSelected(false);secondIP.setSelected(false);thirdIP.setSelected(false);
                mTextPort.setSelected(false);mTextPortRecv.setSelected(false);}
        });
        mTextPort.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()){firstIP.setSelected(false);secondIP.setSelected(false);thirdIP.setSelected(false);fourthIP.setSelected(false);
                mTextPortRecv.setSelected(false);}
        });
        mTextPortRecv.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()){firstIP.setSelected(false);secondIP.setSelected(false);thirdIP.setSelected(false);fourthIP.setSelected(false);
                mTextPort.setSelected(false);}
        });

        mBtnBack = view.findViewById(R.id.btn_net_back);
        mBtnBack.setOnClickListener(v -> {
            initIPAndPort();
            ((DogControllerActivity)fragmentActivity).onNetCancel();
        });
        mBtnCancel = view.findViewById(R.id.btn_net_cancel);
        mBtnCancel.setOnClickListener(v -> {
            initIPAndPort();
            ((DogControllerActivity)fragmentActivity).onNetCancel();
        });
        mBtnOK = view.findViewById(R.id.btn_net_ok);
        mBtnOK.setOnClickListener(v -> {
            String IP_1 = firstIP.getText().toString();
            String IP_2 = secondIP.getText().toString();
            String IP_3 = thirdIP.getText().toString();
            String IP_4 = fourthIP.getText().toString();
            String PORT = mTextPort.getText().toString();
            String PORT_RECV = mTextPortRecv.getText().toString();

            if (IP_1.isEmpty() || IP_2.isEmpty() ||
                IP_3.isEmpty() || IP_4.isEmpty() ||
                PORT.isEmpty() || PORT_RECV.isEmpty()){
                MainApp.toast("请填写所有参数. ", 2000);
                return;
            }

            int nPort = Integer.parseInt(mTextPort.getText().toString());
            if (nPort <= 1024){
                MainApp.toast("Port须大于1024. ", 2000);
                return;
            }
            int nPortRecv = Integer.parseInt(mTextPortRecv.getText().toString());
            if (nPortRecv <= 1024){
                MainApp.toast("Port须大于1024. ", 2000);
                return;
            }

            MainApp.IP_1 = IP_1;
            MainApp.IP_2 = IP_2;
            MainApp.IP_3 = IP_3;
            MainApp.IP_4 = IP_4;
            MainApp.PORT = PORT;
            MainApp.PORT_RECV = PORT_RECV;

            String dirPath = MainApp.getProductDir();
            Log.i("[IP]", dirPath);
            String filePath = dirPath + "/IP_PORT";
            String fileContent = MainApp.IP_1 + "." + MainApp.IP_2 + "." + MainApp.IP_3 + "." + MainApp.IP_4 + ":" + MainApp.PORT;
            if (!FileOperator.writeString(filePath,fileContent)){
                MainApp.toast("文件写入失败，请检查软件权限。",2000);
                return;
            }

            ((DogControllerActivity)fragmentActivity).onNetOK();
        });

        mBtnNum0 = view.findViewById(R.id.btn_0);
        mBtnNum0.setFocusable(false);
        mBtnNum0.setOnClickListener(v -> {
            onNumBtnClick(0);
        });
        mBtnNum1 = view.findViewById(R.id.btn_1);
        mBtnNum1.setFocusable(false);
        mBtnNum1.setOnClickListener(v -> {
            onNumBtnClick(1);
        });
        mBtnNum2 = view.findViewById(R.id.btn_2);
        mBtnNum2.setFocusable(false);
        mBtnNum2.setOnClickListener(v -> {
            onNumBtnClick(2);
        });
        mBtnNum3 = view.findViewById(R.id.btn_3);
        mBtnNum3.setFocusable(false);
        mBtnNum3.setOnClickListener(v -> {
            onNumBtnClick(3);
        });
        mBtnNum4 = view.findViewById(R.id.btn_4);
        mBtnNum4.setFocusable(false);
        mBtnNum4.setOnClickListener(v -> {
            onNumBtnClick(4);
        });
        mBtnNum5 = view.findViewById(R.id.btn_5);
        mBtnNum5.setFocusable(false);
        mBtnNum5.setOnClickListener(v -> {
            onNumBtnClick(5);
        });
        mBtnNum6 = view.findViewById(R.id.btn_6);
        mBtnNum6.setFocusable(false);
        mBtnNum6.setOnClickListener(v -> {
            onNumBtnClick(6);
        });
        mBtnNum7 = view.findViewById(R.id.btn_7);
        mBtnNum7.setFocusable(false);
        mBtnNum7.setOnClickListener(v -> {
            onNumBtnClick(7);
        });
        mBtnNum8 = view.findViewById(R.id.btn_8);
        mBtnNum8.setFocusable(false);
        mBtnNum8.setOnClickListener(v -> {
            onNumBtnClick(8);
        });
        mBtnNum9 = view.findViewById(R.id.btn_9);
        mBtnNum9.setFocusable(false);
        mBtnNum9.setOnClickListener(v -> {
            onNumBtnClick(9);
        });
        mBtnNumBack = view.findViewById(R.id.btn_num_back);
        mBtnNumBack.setFocusable(false);
        mBtnNumBack.setOnClickListener(v -> {
            delNumFromTextView();
        });
        mBtnNumOK = view.findViewById(R.id.btn_num_ok);
        mBtnNumOK.setFocusable(false);
        mBtnNumOK.setOnClickListener(v -> {
            onNumBtnOK();
        });

        InputMethodManager imm = (InputMethodManager) fragmentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(firstIP.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(secondIP.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(thirdIP.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(fourthIP.getWindowToken(), 0);
        imm.showSoftInput(firstIP, 0);
        imm.showSoftInput(secondIP, 0);
        imm.showSoftInput(thirdIP, 0);
        imm.showSoftInput(fourthIP, 0);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initIPAndPort();
    }
    void initIPAndPort(){
        firstIP.setText(MainApp.IP_1);
        secondIP.setText(MainApp.IP_2);
        thirdIP.setText(MainApp.IP_3);
        fourthIP.setText(MainApp.IP_4);
        mTextPort.setText(MainApp.PORT);
        mTextPortRecv.setText(MainApp.PORT_RECV);
    }
    private void addNumToTextView(int num, TextView v){
        String s = v.getText().toString();
        if (s.length() == 3 && v != mTextPort && v != mTextPortRecv){
            MainApp.toast("最多输入3个数字。", Toast.LENGTH_LONG);
            return;
        }
        s += num;

        int IPValue = Integer.parseInt(s);
        if (IPValue > 255 && v != mTextPort && v != mTextPortRecv){
            MainApp.toast("请输入小于255的数字。", Toast.LENGTH_LONG);
            return;
        }
        v.setText(s);
    }
    private void onNumBtnClick(int num){
        if (firstIP.isSelected()){
            addNumToTextView(num, firstIP);
        }
        else if (secondIP.isSelected()){
            addNumToTextView(num, secondIP);
        }
        else if (thirdIP.isSelected()){
            addNumToTextView(num, thirdIP);
        }
        else if (fourthIP.isSelected()){
            addNumToTextView(num, fourthIP);
        }
        else if (mTextPort.isSelected()){
            addNumToTextView(num, mTextPort);
        }
        else if (mTextPortRecv.isSelected()){
            addNumToTextView(num, mTextPortRecv);
        }
    }
    private void onNumBtnOK() {
        if (firstIP.isSelected()){
            firstIP.setSelected(false);
            secondIP.setSelected(true);
        }
        else if (secondIP.isSelected()){
            secondIP.setSelected(false);
            thirdIP.setSelected(true);
        }
        else if (thirdIP.isSelected()){
            thirdIP.setSelected(false);
            fourthIP.setSelected(true);
        }
        else if (fourthIP.isSelected()){
            fourthIP.setSelected(false);
            mTextPort.setSelected(true);
        }
        else if (mTextPort.isSelected()){
            mTextPort.setSelected(false);
        }
        else if (mTextPortRecv.isSelected()){
            mTextPortRecv.setSelected(false);
        }
    }
    private void delNumFromTextView(TextView v){
        String s = v.getText().toString();
        if (s.isEmpty()){
            return;
        }

        s = s.substring(0, s.length() - 1);
        v.setText(s);
    }
    private void delNumFromTextView() {
        if (firstIP.isSelected()){
            delNumFromTextView(firstIP);
        }
        else if (secondIP.isSelected()){
            delNumFromTextView(secondIP);
        }
        else if (thirdIP.isSelected()){
            delNumFromTextView(thirdIP);
        }
        else if (fourthIP.isSelected()){
            delNumFromTextView(fourthIP);
        }
        else if (mTextPort.isSelected()){
            delNumFromTextView(mTextPort);
        }
        else if (mTextPortRecv.isSelected()){
            delNumFromTextView(mTextPortRecv);
        }
    }
    public void setIPEditTextListener() {
        //设置第一个字段的事件监听
        firstIP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) fragmentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(firstIP.getWindowToken(), 0);

                imm.hideSoftInputFromWindow(firstIP.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        });
        secondIP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) fragmentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(secondIP.getWindowToken(), 0);
            }
        });
        thirdIP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) fragmentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(thirdIP.getWindowToken(), 0);
            }
        });
        fourthIP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) fragmentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(fourthIP.getWindowToken(), 0);
            }
        });
        firstIP.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                Log.i("test", s.toString());
                int index = s.length();
                if (null != s && index > 0) {
                    if (index > 3) {//如果位数大于3，则直接下一个控件获取光标
                        secondIP.setFocusable(true);
                        secondIP.requestFocus();
                    } else {//如果位数不大于3，则判断是否大于255,
                        if (Integer.parseInt(s.toString()) > 255) {
                            MainApp.toast("IP大小在0-255之间", Toast.LENGTH_LONG);
                            return;
                        }
                        sFirstIP = s.toString().trim();
                    }
                } else {
                    sFirstIP = "";//这一步必须写，否则无法更换最后一位数字
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                firstIP.removeTextChangedListener(this);
                firstIP.setText(sFirstIP);
                firstIP.addTextChangedListener(this);
            }
        });
        //设置第二个IP字段的事件监听
        secondIP.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                int index = s.length();
                if (null != s && index > 0) {
                    if (index > 3) {
                        thirdIP.setFocusable(true);
                        thirdIP.requestFocus();
                    } else {
                        if (Integer.parseInt(s.toString()) > 255) {
                            MainApp.toast("IP大小在0-255之间", Toast.LENGTH_LONG);
                            return;
                        }
                        sSecondIP = s.toString().trim();
                    }

                } else {
                    sSecondIP = "";
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                secondIP.removeTextChangedListener(this);
                secondIP.setText(sSecondIP);
                secondIP.addTextChangedListener(this);
            }
        });
        //设置第三个IP字段的事件监听
        thirdIP.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                int index = s.length();
                if (null != s && index > 0) {
                    if (index > 3) {
                        fourthIP.setFocusable(true);
                        fourthIP.requestFocus();
                    } else {
                        if (Integer.parseInt(s.toString()) > 255) {
                            MainApp.toast("IP大小在0-255之间", Toast.LENGTH_LONG);
                            return;
                        }
                        sThirdIP = s.toString().trim();
                    }
                } else {
                    sThirdIP = "";
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                thirdIP.removeTextChangedListener(this);
                thirdIP.setText(sThirdIP);
                thirdIP.addTextChangedListener(this);
            }
        });
        //设置第四个IP字段的事件监听
        fourthIP.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                int index = s.length();
                if (null != s && index > 0) {
                    if (index > 3) {
                        mTextPort.setFocusable(true);
                        mTextPort.requestFocus();
                    } else {//如果
                        if (Integer.parseInt(s.toString()) > 255) {
                            MainApp.toast("请输入合法的ip地址", Toast.LENGTH_LONG);
                            return;
                        }
                        sFourthIP = s.toString().trim();
                    }
                } else {
                    sFourthIP = "";
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                fourthIP.removeTextChangedListener(this);
                fourthIP.setText(sFourthIP);//最终的取值
                fourthIP.addTextChangedListener(this);
            }
        });
    }
}
